package com.amao.ws.websocket.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.Extension;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

public class WsConfigurator extends Configurator{
	
	@Override
	public String getNegotiatedSubprotocol(List<String> supported, List<String> requested) {
		return super.getNegotiatedSubprotocol(supported, requested);
	}

	@Override
	public List<Extension> getNegotiatedExtensions(List<Extension> installed, List<Extension> requested) {
		return super.getNegotiatedExtensions(installed, requested);
	}

	@Override
	public boolean checkOrigin(String originHeaderValue) {
		return super.checkOrigin(originHeaderValue);
	}

	@Override
	public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> mHeaders = request.getHeaders();
        Map<String,String> headers = new HashMap<String,String>();
        
        //获取HTTP头token
        if(null != mHeaders.get("token") && mHeaders.get("token").size()>0) {
        	headers.put("token", mHeaders.get("token").get(0));
        	headers.put("appType", "Android");
        }else {
        	headers.put("appType", "WeiXin");
        	//可能是微信端
        	if(null != mHeaders.get("sec-websocket-protocol") && mHeaders.get("sec-websocket-protocol").size()>0) {
        		headers.put("token", mHeaders.get("sec-websocket-protocol").get(0));
    			response.getHeaders().put("sec-websocket-protocol", mHeaders.get("sec-websocket-protocol"));
    		}
        }
        
        //获取HTTP头version
        if(null != mHeaders.get("soft_version") && mHeaders.get("soft_version").size()>0) {
        	headers.put("soft_version", mHeaders.get("soft_version").get(0));
        }else {
        	headers.put("soft_version", "");
        }
        
        //获取HTTP头role
        if(null != mHeaders.get("role") && mHeaders.get("role").size()>0) {
        	headers.put("role", mHeaders.get("role").get(0));
        }else {
        	headers.put("role", "");
        }
        
        //获取HTTP头account
        if(null != mHeaders.get("account") && mHeaders.get("account").size()>0) {
        	headers.put("account", mHeaders.get("account").get(0));
        }else {
        	headers.put("account", "");
        }
        
		sec.getUserProperties().put("HttpHeader", headers);
		
		super.modifyHandshake(sec, request, response);
	}

	@Override
	public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
		return super.getEndpointInstance(endpointClass);
	}

}
